package com.yimingkeji.security.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @Describe:
 * @Auther: zhenlong.yang
 * @Date: 2019/1/3 14:49
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * http访问控制
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/login").permitAll()//允许访问
                .anyRequest().authenticated()//其他所有url都需要鉴权，如果未登陆则跳转登陆页面
            .and()
                .formLogin()
                    .loginPage("/login")//指定登录页面地
                    .loginProcessingUrl("/login")//登录处理url
                    .successForwardUrl("/home")//登录成功后跳转url
                    .permitAll()//允许访问
            .and()
                .logout().logoutUrl("/loginout").permitAll();//指定登出url，并且允许访问
    }

    /**
     * 全局配置：
     *  创建一个内存用户
     *    用户名 admin
     *    密码 admin
     *    角色 USER
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //新版本security框架这里需要指定密码加密方式，不然报错：There is no PasswordEncoder mapped for the id “null”
        BCryptPasswordEncoder pwdEncoder = new BCryptPasswordEncoder();
        auth.inMemoryAuthentication()
                .passwordEncoder(pwdEncoder)
                .withUser("admin")
                .password(pwdEncoder.encode("admin"))
                .roles("ADMIN");
    }
}
